package com.yangrd.helper.crudhelper.core.crud.page.impl;

import com.yangrd.helper.crudhelper.core.crud.page.CrudPage;
import com.yangrd.helper.crudhelper.core.crud.page.CrudPageRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * description: ComposeCrudPageRepository
 *
 * @author: yangrd
 * @date: 2020/10/23
 * @version: 1.0
 */
@RequiredArgsConstructor
public class ComposeCrudPageRepository implements CrudPageRepository {

    private final List<CrudPageRepository> crudPageRepositories;

    @Override
    public Optional<CrudPage> get(Class<?> domainClass) {
        for (int i = 0; i < crudPageRepositories.size(); i++) {
            CrudPageRepository repository = crudPageRepositories.get(i);
            Optional<CrudPage> optional = repository.get(domainClass);
            if (optional.isPresent()) {
                if (i != 0) {
                    put(domainClass, optional.get());
                }
                return optional;
            }
        }
        return Optional.empty();
    }

    @Override
    public void put(Class<?> domainClass, CrudPage crudPage) {
        crudPageRepositories.forEach(crudPageRepository -> {
            crudPageRepository.put(domainClass, crudPage);
        });
    }

    @Override
    public void delete(Class<?> domainClass) {
        crudPageRepositories.forEach(crudPageRepository -> crudPageRepository.delete(domainClass));
    }

    @Override
    public Page<CrudPage> findAll(String domain, Pageable pageable) {
        if (crudPageRepositories.isEmpty()) {
            return new PageImpl<>(Collections.emptyList());
        }
        CrudPageRepository repository = crudPageRepositories.get(crudPageRepositories.size() - 1);
        return repository.findAll(domain, pageable);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
